
package com.vodafone.nowplus.android.peoplemail.singlesignon;

import java.io.StringBufferInputStream;
import java.io.StringReader;
import java.security.Key;

import javax.crypto.Cipher;

/**
 * 
 * Class for RSA encryption and decryption. 
 * 
 *
 */
public class RSACrypter {

    /**
     * Converts a byte array to a String of hex values
     * 
     * @param b byte Array
     * @return String in hex format
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * Converts a hex String in to a byte array
     * 
     * @param s String in hex format
     * @return byte Array
     */
    public static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte)v;
        }
        return b;
    }

    /**
     * Encrypts an String using RSA public key encryption
     * 
     * @param in input String to be encrypted
     * @param key public key
     * @return encrypted String in hex format
     * @throws Exception
     */
    public static String enCrypt(String in, Key key) throws Exception {
        if (in == null || in.length() == 0) {
            return in;
        }
        Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherData = cipher.doFinal(in.getBytes());
        return byteArrayToHexString(cipherData);
    }

    /**
     * Decrypts an String using RSA public key encryption
     * 
     * @param in input String in hex format to be decrypted
     * @param key private key
     * @return decrypted String
     * @throws Exception
     */
    public static String deCrypt(String in, Key key) throws Exception {
        if (in == null || in.length() == 0) {
            return in;
        }
        Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] buffer = cipher.doFinal(hexStringToByteArray(in));
        return new String(buffer);
    }

}
